////////////////////////////////////////////////
// File: NewsController.java
// Description: Enter summary here after generation.
// Date: 2016-09-23 09:09:34
// Web: http://www.elanzhou.com/
////////////////////////////////////////////////
package com.mvc.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.mvc.entity.Meminfo;
//import com.mvc.entity.User;
//import com.mvc.entity.UserDetail;
import com.mvc.entity.News;
import com.mvc.service.DictService;
import com.mvc.service.NewsService;
import com.mvc.service.SyscateService;
import com.mvc.service.SyschannelService;
import com.pub.MyJson;
import com.pub.Page;
import com.aspose.cells.Cells;
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;
@Controller
@RequestMapping("News")
public class NewsController {
	protected final transient Log logger = LogFactory.getLog(NewsController.class);
	@Autowired
	private NewsService newsService;

	@Autowired
	private SyschannelService syschannelService;//栏目service
	@Autowired
	private SyscateService syscateService;//品类service
	@Autowired
	private DictService dictService;
	
	public NewsController() {
	}

	/*列表*/
	@RequestMapping("Index.do")
	public String Index(HttpSession session,ModelMap modelMap, String pageNo, String Ajax) {
		Meminfo smeminfo=(Meminfo) session.getAttribute("SessionMem");
		modelMap.put("smeminfo",smeminfo);
		
		Page page = new Page();
		page.setPageNox(pageNo);
		page.setPageSize(15);
		String hql = "select a from News a order by a.ID desc";
		List list = newsService.getNewsList(hql, page);
		String counthql = "select count(*) from News a";
		page.setPageCount(newsService.getCount(counthql, page));
		modelMap.put("page", page);
		modelMap.put("list", list);
		if (Ajax != null && Ajax.equals("Ajax")) {
			return "/News/List";
		} else {
			return "/News/Index";
		}

	}
	/*添加*/ 
	@RequestMapping("Add.do")
	public String Add(HttpSession session,ModelMap modelMap)
	{
		Meminfo smeminfo=(Meminfo) session.getAttribute("SessionMem");
		modelMap.put("smeminfo",smeminfo);
		List hylist=dictService.getAllByKeyname("新闻类型");		
		modelMap.put("hylist",hylist);
		//获取栏目列表
		List<Object> channelList=syschannelService.getListByHql("select a from Syschannel a order by a.ID desc");
		modelMap.put("channelList", channelList);
		//加载品类列表
		List<Object> fcate=syscateService.getFcate() ;
		modelMap.put("fcate", fcate);
		Date date=new Date();
		DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
		String dqsj=format.format(date);
		modelMap.put("dqsj", dqsj);
		return "/News/Add";
	}
	/*保存*/
	@RequestMapping("Save.do")
	public void Save(HttpSession session,HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap) {
		Meminfo smeminfo=(Meminfo) session.getAttribute("SessionMem");
		modelMap.put("smeminfo",smeminfo);
		
		try {
			
			News  news= new News();
			boolean tag=true;
		    String Msg="信息保存成功";
             
               if(tag){
                              
               String FieldTitle=(String)request.getParameter("Title");
             
               if(((FieldTitle!=null)&(!FieldTitle.trim().equals("")))){
            	   FieldTitle=FieldTitle.trim();
                    news.setTitle(FieldTitle);
                  
        		}else
        		{
        			tag=false;
        			Msg="标题不能为空！";
        		}
        		}
	         
             
               if(tag){
                              
               String FieldSyschannel=(String)request.getParameter("Syschannel");
             
               if(((FieldSyschannel!=null)&(!FieldSyschannel.trim().equals("")))){
            	   FieldSyschannel=FieldSyschannel.trim();
                    news.setSyschannel(FieldSyschannel);
                  
        		}else
        		{
        			tag=false;
        			Msg="栏目不能为空！";
        		}
        		}
	         
             
               if(tag){
                              
               String FieldFname=(String)request.getParameter("Fname");
             
               if(((FieldFname!=null)&(!FieldFname.trim().equals("")))){
            	   FieldFname=FieldFname.trim();
                    news.setFname(FieldFname);
                  
        		}else
        		{
        			tag=false;
        			Msg="所属品类不能为空！";
        		}
        		}
	         
             
               if(tag){
                              
               String FieldCatename=(String)request.getParameter("Catename");
             
               if(((FieldCatename!=null)&(!FieldCatename.trim().equals("")))){
            	   FieldCatename=FieldCatename.trim();
                    news.setCatename(FieldCatename);
                  
        		}else
        		{
        			tag=false;
        			Msg="所属品种不能为空！";
        		}
        		}
               
               if(tag){
                   
                   String FieldNewstype=(String)request.getParameter("Newstype");
                 
                   if(((FieldNewstype!=null)&(!FieldNewstype.trim().equals("")))){
                	   FieldNewstype=FieldNewstype.trim();
                        news.setNewstype(FieldNewstype);
                      
            		}else
            		{
            			tag=false;
            			Msg="新闻类型不能为空！";
            		}
            		}
               
               
               if(tag){
                   
                   String FieldNewspic=(String)request.getParameter("Newspic");
                 
                   if(((FieldNewspic!=null)&(!FieldNewspic.trim().equals("")))){
                	   FieldNewspic=FieldNewspic.trim();
                        news.setNewspic(FieldNewspic);
                      
            		}else
            		{
            			 FieldNewspic="/upfile/news.jpg";
                         news.setNewspic(FieldNewspic);
            			/*tag=false;
            			Msg="图片不能为空！";*/
            		}
            		}
                           
	         
             
               if(tag){
                              
               String FieldInfodate=(String)request.getParameter("Infodate");
             
               if(((FieldInfodate!=null)&(!FieldInfodate.trim().equals("")))){
            	   FieldInfodate=FieldInfodate.trim();
                    news.setInfodate(FieldInfodate);
                  
        		}else
        		{
        			tag=false;
        			Msg="发布时间不能为空！";
        		}
        		}
	         
             
               if(tag){
                              
               String FieldInfocontent=(String)request.getParameter("Infocontent");
             
               if(((FieldInfocontent!=null)&(!FieldInfocontent.trim().equals("")))){
            	   FieldInfocontent=FieldInfocontent.trim();
                    news.setInfocontent(FieldInfocontent);
                  
        		}else
        		{
        			tag=false;
        			Msg="内容不能为空！";
        		}
        		}
	         
             
               if(tag){
                              
               String FieldMemname=(String)request.getParameter("Memname");
             
               if(((FieldMemname!=null)&(!FieldMemname.trim().equals("")))){
            	   FieldMemname=FieldMemname.trim();
                    news.setMemname(FieldMemname);
                  
        		}else
        		{
        			tag=false;
        			Msg="发布人不能为空！";
        		}
        		}
	         
            
            MyJson mj=new MyJson();
              if(tag){
                     newsService.Save(news);	 
        			 mj.setStatusCode(200);
        		 }else
        		 {
        			 mj.setStatusCode(300);
        		 }
             mj.setMessage(Msg);
             mj.setForwardUrl("/News/Index.do");
             mj.setCallbackType("forward");
             String str=mj.getJson();
			 response.getWriter().print(str);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	} 
    
	/*编辑*/
	@RequestMapping("Edit.do")
	public String Edit(HttpSession session,HttpServletRequest request,ModelMap modelMap)
	{
		Meminfo smeminfo=(Meminfo) session.getAttribute("SessionMem");
		modelMap.put("smeminfo",smeminfo);
		
		String ID=request.getParameter("ID");
		News news=(News)newsService.getNews(ID);
		modelMap.put("news", news);
		//获取栏目列表
		List<Object> channelList=syschannelService.getListByHql("select a from Syschannel a order by a.ID desc");
		modelMap.put("channelList", channelList);
		//加载品类列表
		List<Object> fcate=syscateService.getFcate() ;
		modelMap.put("fcate", fcate);
		List hylist=dictService.getAllByKeyname("新闻类型");		
		modelMap.put("hylist",hylist);
		return "/News/Edit";
	}
    
    /*编辑保存*/
	@RequestMapping("EditSave.do")
	public void EditSave(HttpSession session,HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap) {
		Meminfo smeminfo=(Meminfo) session.getAttribute("SessionMem");
		modelMap.put("smeminfo",smeminfo);
		
		try {
			String Id=(String)request.getParameter("ID");
			News  news=(News)newsService.getNews(Id);
			boolean tag=true;
		    String Msg="信息修改成功";
             
            if(tag){
               
               String FieldTitle=(String)request.getParameter("Title");
             
               if(((FieldTitle!=null)&(!FieldTitle.trim().equals("")))){
            	   FieldTitle=FieldTitle.trim();
                    news.setTitle(FieldTitle);
                  
        		}else
        		{
        			tag=false;
        			Msg="标题不能为空！";
        		}
        		}
	         
             
            if(tag){
               
               String FieldSyschannel=(String)request.getParameter("Syschannel");
             
               if(((FieldSyschannel!=null)&(!FieldSyschannel.trim().equals("")))){
            	   FieldSyschannel=FieldSyschannel.trim();
                    news.setSyschannel(FieldSyschannel);
                  
        		}else
        		{
        			tag=false;
        			Msg="栏目不能为空！";
        		}
        		}
	         
             
            if(tag){
               
               String FieldFname=(String)request.getParameter("Fname");
             
               if(((FieldFname!=null)&(!FieldFname.trim().equals("")))){
            	   FieldFname=FieldFname.trim();
                    news.setFname(FieldFname);
                  
        		}else
        		{
        			tag=false;
        			Msg="所属品类不能为空！";
        		}
        		}
	         
             
            if(tag){
               
               String FieldCatename=(String)request.getParameter("Catename");
             
               if(((FieldCatename!=null)&(!FieldCatename.trim().equals("")))){
            	   FieldCatename=FieldCatename.trim();
                    news.setCatename(FieldCatename);
                  
        		}else
        		{
        			tag=false;
        			Msg="所属品种不能为空！";
        		}
        		}
	         
            if(tag){
                
                String FieldNewstype=(String)request.getParameter("Newstype");
              
                if(((FieldNewstype!=null)&(!FieldNewstype.trim().equals("")))){
             	   FieldNewstype=FieldNewstype.trim();
                     news.setNewstype(FieldNewstype);
                   
         		}else
         		{
         			tag=false;
         			Msg="新闻类型不能为空！";
         		}
         		}
            
            
            if(tag){
                
                String FieldNewspic=(String)request.getParameter("Newspic");
              
                if(((FieldNewspic!=null)&(!FieldNewspic.trim().equals("")))){
             	   FieldNewspic=FieldNewspic.trim();
                     news.setNewspic(FieldNewspic);
                   
         		}else
         		{
         			 FieldNewspic="/upfile/news.jpg";
                      news.setNewspic(FieldNewspic);
         			/*tag=false;
         			Msg="图片不能为空！";*/
         		}
         		}
            
            
            if(tag){
               
               String FieldInfodate=(String)request.getParameter("Infodate");
             
               if(((FieldInfodate!=null)&(!FieldInfodate.trim().equals("")))){
            	   FieldInfodate=FieldInfodate.trim();
                    news.setInfodate(FieldInfodate);
                  
        		}else
        		{
        			tag=false;
        			Msg="发布时间不能为空！";
        		}
        		}
	         
             
            if(tag){
               
               String FieldInfocontent=(String)request.getParameter("Infocontent");
             
               if(((FieldInfocontent!=null)&(!FieldInfocontent.trim().equals("")))){
            	   FieldInfocontent=FieldInfocontent.trim();
                    news.setInfocontent(FieldInfocontent);
                  
        		}else
        		{
        			tag=false;
        			Msg="内容不能为空！";
        		}
        		}
	         
             
            if(tag){
               
               String FieldMemname=(String)request.getParameter("Memname");
             
               if(((FieldMemname!=null)&(!FieldMemname.trim().equals("")))){
            	   FieldMemname=FieldMemname.trim();
                    news.setMemname(smeminfo.getMemname());
                  
        		}else
        		{
        			tag=false;
        			Msg="发布人不能为空！";
        		}
        		}
	         
            
            MyJson mj=new MyJson();
              if(tag){
                     newsService.EditSave(news);	 
        			 mj.setStatusCode(200);
        		 }else
        		 {
        			 mj.setStatusCode(300);
        		 }
             mj.setMessage(Msg);
             mj.setForwardUrl("/News/Index.do");
             mj.setCallbackType("forward");
             String str=mj.getJson();
			 response.getWriter().print(str);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	} 
    
	/*删除*/
	@RequestMapping("Del.do")
	public void Del(HttpSession session,HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap) {
		Meminfo smeminfo=(Meminfo) session.getAttribute("SessionMem");
		modelMap.put("smeminfo",smeminfo);
		
             String ID=request.getParameter("ID");
             newsService.Del(ID);
             String Msg="数据删除成功";
             MyJson mj=new MyJson();
             mj.setStatusCode(200);
             mj.setMessage(Msg);
             mj.setForwardUrl("/News/Index.do");
             mj.setCallbackType("forward");
             String str=mj.getJson();
             try {
                  response.getWriter().print(str);
                 } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
                 }
	      }
          	/*编辑*/
	@RequestMapping("Detail.do")
	public String Detail(HttpSession session,HttpServletRequest request,ModelMap modelMap)
	{
		Meminfo smeminfo=(Meminfo) session.getAttribute("SessionMem");
		modelMap.put("smeminfo",smeminfo);
		
		String ID=request.getParameter("ID");
		News news=(News)newsService.getNews(ID);
		modelMap.put("news", news);
		return "/News/Detail";
	}
    
	@RequestMapping("CkeditorUpload.do")
	public void CkeditorUpload(HttpSession session,ModelMap modelMap,HttpServletRequest request,HttpServletResponse resp,@RequestParam(value="upload", required=false) MultipartFile upload){
		Meminfo smeminfo=(Meminfo) session.getAttribute("SessionMem");
		modelMap.put("smeminfo",smeminfo);		
        
        String uploadDir = request.getRealPath("/")+"upload";  
        File dirPath = new File(uploadDir);  
        if (!dirPath.exists()) {  
            dirPath.mkdirs();  
        }  
        String   fileName=java.util.UUID.randomUUID().toString();
        File f =new File(upload.getOriginalFilename());
        String extName=f.getName();
        String prefix=extName.substring(extName.lastIndexOf(".")+1);
        fileName=fileName+"."+prefix;
        String xpath="/upload/"+fileName;
        String sep = System.getProperty("file.separator");  
        File uploadedFile = new File(uploadDir + sep  
                +fileName );  
        try {
        	  byte[] bytes;
    		  bytes = upload.getBytes();
   			  FileCopyUtils.copy(bytes, uploadedFile);
			  bytes=null;
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
       
    
        
            try {
                //保存图片
            	//FileCopyUtils.copy(upload.getBytes() , picFile);
                //返回数据
                resp.setHeader("Content-type", "text/html;charset=UTF-8"); 
                resp.setCharacterEncoding("UTF-8");


                StringBuffer sb = new StringBuffer();  
                sb.append("<script type=\"text/javascript\">");  
                sb.append("window.parent.CKEDITOR.tools.callFunction(1,'"+xpath+"' , '文件上传成功!');");  
                sb.append("</script>"); 

                resp.getWriter().write(sb.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
       
    }
}
